<?php
use App\Models\UserFile;
use App\Models\Storage;
use Illuminate\Support\Facades\Cache;
use App\Models\ParameterItem;
use App\Models\ServeUser;
use App\Models\User;
use App\Models\ChannelSource;
if (! function_exists('model')) {

	/**
	 * 取得模型实例
	 *
	 * @return Model
	 */
	function model($name)
	{
		$name = 'App\Models\\' . $name;
		return new $name();
	}
}

if (! function_exists('subdomain')) {

	/**
	 * 取得访问的子域名
	 *
	 * @return string
	 */
	function subdomain()
	{
		$matchs = array();
		$request = Request::instance();
		$host = $request->headers->get('host');
		$host = str_replace(parse_url(config('app.url'), PHP_URL_HOST), '', $host);
		preg_match('/([^.]+)\./i', $host, $matchs);
		return (string) @$matchs[1];
	}
}

if (! function_exists('subport')) {

	/**
     * 取得访问的端口号
     *
     * @return string
     */
	function subport()
	{
		$request = Request::instance();
		$port = $request->server->get('SERVER_PORT');
		return (string) @$port;
	}
}

if (! function_exists('load_routes')) {

	/**
	 * 自动装载路由表
	 */
	function load_routes($dir)
	{
		foreach (glob($dir . '/*') as $filename) {
			if (is_dir($filename)) {
				load_routes($filename);
			} elseif (is_file($filename)) {
				require $filename;
			}
		}
	}
}

if (! function_exists('uniqueid')) {

	/**
	 * 创建一个分布式唯一ID
	 *
	 * @return string
	 */
	function uniqueid()
	{
		$uniqid = uniqid(gethostname(), true);
		$md5 = substr(md5($uniqid), 12, 8); // 8位md5
		$uint = hexdec($md5);
		return sprintf('%s%010u', date('Ymd'), $uint);
	}
}

if (! function_exists('hash_id')) {

	/**
	 * 计算一个hashID
	 *
	 * @return string
	 */
	function hash_id()
	{
		$data = func_get_args();
		sort($data, SORT_STRING);
		return md5(join(':', $data));
	}
}

if (! function_exists('get_distance')) {

	/**
	 * 获取两个坐标间的距离
	 *
	 * @return float
	 */
	function get_distance($lat1, $lng1, $lat2, $lng2)
	{
		$lat1 = floatval($lat1);
		$lng1 = floatval($lng1);
		$lat2 = floatval($lat2);
		$lng2 = floatval($lng2);
		// 地球半径。
		static $earth_radius = 6378.137;

		// 计算两个坐标间距离。
		$rad_lat1 = rad2deg($lat1);
		$rad_lat2 = rad2deg($lat2);
		$a = $rad_lat1 - $rad_lat2;
		$b = rad2deg($lng1) - rad2deg($lng2);

		$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($rad_lat1) * cos($rad_lat2) * pow(sin($b / 2), 2)));
		$s = $s * $earth_radius;
		$s = round($s * 10000) / 10000;
		return $s;
	}
}

//微信支付相关函数
if (! function_exists('weiXinCreateElement')) {

	/**
     * 创建xml节点
     * @param DOMDocument $dom
     * @param string $key 键
     * @param string $value 值
     * @return DOMElement
     */
	function weiXinCreateElement($dom, $key, $value, $cdate = false)
	{
		$element = $dom->createElement($key);
		$elementValue = $cdate ? $dom->createCDATASection($value) : $dom->createTextNode($value);
		$element->appendChild($elementValue);

		return $element;
	}
}

if (! function_exists('weiXinCreateXml')) {

	/**
     * 创建xml
     * @param array $arrayData 数组内容
     * @return DOMDocument
     */
	function weiXinCreateXml($arrayData, $cdate = false)
	{
		$dom = new DOMDocument();
		$rootElement = $dom->createElement("xml");

		foreach ($arrayData as $key => $value) {
			$rootElement->appendChild(weiXinCreateElement($dom, $key, $value, $cdate));
		}

		$dom->appendChild($rootElement);

		return $dom;
	}
}

if (! function_exists('weiXinCreateSign')) {

	/**
     * 生成签名
     * @param array $arrayData 数组内容
     * @param string $signKey 签名的key
     * @return string
     */
	function weiXinCreateSign($arrayData, $signKey)
	{
		$signString = "";

		ksort($arrayData);

		foreach ($arrayData as $key => $value) {
			if ($key != "sign" && $key != "" && $value != "") {
				$signString .= "$key=$value&";
			}
		}

		$signString .= "key=$signKey";

		return strtoupper(md5($signString));
	}
}

if (! function_exists('weiXinNotifyLog')) {

	/**
     * 打印回调日志
     * @param string $word 日志内容
     */
	function weiXinNotifyLog($word)
	{
		$path = base_path('storage') . DIRECTORY_SEPARATOR;
		$fp = fopen($path . "weixinnotify.log", "a");
		flock($fp, LOCK_EX);
		fwrite($fp, "time：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}
}

//微信支付相关函数 end


//支付宝支付相关函数
/**
 * 解析回调接口获取到的数据
 */
if (! function_exists('resetResponseData')) {

	function resetResponseData($post_data)
	{
		$raw_post_data = explode('&', $post_data);
		foreach ($raw_post_data as $item) {
			$item = urldecode($item);
			$data_items[] = $item;
		}
		sort($data_items);

		$info = [];
		foreach ($data_items as $item) {
			list ($name, $value) = explode('=', $item);
			$info[$name] = $value;
		}

		return $info;
	}
}
//支付宝支付相关函数end


//商城签名函数
if (! function_exists('shopCreateSign')) {

	function shopCreateSign($arrayData, $signKey)
	{
		$signString = "";

		ksort($arrayData);

		foreach ($arrayData as $key => $value) {
			if ($key != "sign" && $key != "" && $value != "") {
				$signString .= "$key=$value&";
			}
		}

		$signString .= "key=$signKey";

		return strtoupper(md5($signString));
	}
}
//end


//获取ip
if (! function_exists('getIP')) {

	function getIP()
	{
		if (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('HTTP_X_FORWARDED')) {
			$ip = getenv('HTTP_X_FORWARDED');
		} elseif (getenv('HTTP_FORWARDED_FOR')) {
			$ip = getenv('HTTP_FORWARDED_FOR');
		} elseif (getenv('HTTP_FORWARDED')) {
			$ip = getenv('HTTP_FORWARDED');
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
}
//end


if (! function_exists('fetchUserFile')) {

	function fetchUserFile($path, $user = null)
	{
		//把图片临时获取到服务器
		$filePath = saveImage($path); //返回文件的绝对地址
		if (! $filePath)
			return false;
			// 取得文件是否已经存在。
		$_hash = md5_file($filePath);
		$storage = Storage::find($_hash);
		if (is_null($storage)) {
			$pathinfo = pathinfo($filePath);
			$_filename = $_hash . '.' . $pathinfo['extension'];
			$_storage = base_path('storage/files') . DIRECTORY_SEPARATOR . $_filename;
			// 存图片。
			if (! file_exists($_storage)) {
				copy($filePath, $_storage);
			}
			// 取得图片尺寸。
			$size = getimagesize($_storage);
			$width = $size[0];
			$height = $size[1];
			$mime = $size['mime'];
			// 存库
			$storage = new Storage();
			$storage->hash = $_hash;
			$storage->format = $pathinfo['extension'] ?  : '';
			$storage->size = filesize($_storage) ?  : 0;
			$storage->width = $width ?  : 0;
			$storage->height = $height ?  : 0;
			$storage->mime = $mime ?  : '';
			$storage->path = $_filename;
			$storage->save();
		}

		$userfile = null;

		if (! is_null($storage)) {
			// 关联用户的文件。
			$userfile = new UserFile();
			if (! is_null($user)) {
				$userfile->user()->associate($user);
			}
			$userfile->storage()->associate($storage);
			$userfile->filename = basename($path);
			$userfile->save();
		}

		return $userfile;
	}
}

if (! function_exists('saveImage')) {

	/**
     * 根据图片的地址保存图片到本地指定的路径
     * @param type $url 图片的最终地址
     * @param type $path 文件保存到的路径
     * @param type $isFollowLocation 图片地址是否302跳转
     * @return string   返回图片的地址
     */
	function saveImage($url, $path = '/')
	{
		//定义一个临时文件夹
		$imgTemp = base_path('storage/files') . '/tempImg';
		if (! file_exists($imgTemp)) {
			mkdir($imgTemp, 0755, true);
		}
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //返回文本流
		$imageData = curl_exec($curl);
		$httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
		curl_close($curl);
		
// 		if (preg_match('#404#', $imageData)) {
// 			return '';
// 		}
		if($httpCode == 404 || $httpCode == 302){
			return '';
		}
		$files = pathinfo($url);

		if (! array_key_exists("extension", $files)) {
			$filename = sprintf('%s%s.%s', $path, date('Ymd', time()) . md5($files['filename'] . time()), '.jpg');
		} else {
			$filename = sprintf('%s%s.%s', $path, date('Ymd', time()) . md5($files['filename'] . time()), $files['extension']);
		}

		if (! file_exists($imgTemp . $filename)) { //创建一个新图片
			$tp = @fopen($imgTemp . $filename, 'a');
			fwrite($tp, $imageData);
			fclose($tp);
			return $imgTemp . $filename;
		} else {
			return $imgTemp . $filename;
		}
	}
}

/**
 *  格式化时间格式
 */
if (! function_exists('timeformat')) {

	function timeformat($format, $time)
	{
		return date($format, strtotime($time));
	}
}

/**
 *  别名变参数
 */
if (! function_exists('alias2parameter ')) {

	function alias2parameter($alias)
	{
		preg_match_all('/([a-zA-z])([0-9]+)/', $alias, $match);
		$data = [];
		foreach ($match[1] as $key => $item) {
			$data[$item] = $match[2][$key];
		}
		return $data;
	}
}

/**
 * 微信分享jssdk
 */
if (! function_exists('getSignPackage')) {

	function getSignPackage($appid = '', $appsecret = '')
	{
		$jsapiTicket = getJsApiTicket($appid, $appsecret);

		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$timestamp = time();
		$nonceStr = createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);

		$signPackage = array(
			"appId" => $appid,
			"nonceStr" => $nonceStr,
			"timestamp" => $timestamp,
			"url" => $url,
			"signature" => $signature,
			"rawString" => $string
		);

		return $signPackage;
	}
}
if (! function_exists('getJsApiTicket')) {

	function getJsApiTicket($appid, $appsecret)
	{
		// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
		$cache_key = md5('weixin_jssdk_jsapi_ticket');
		$accessToken = getAccessToken($appid, $appsecret);
		if (Cache::has($cache_key)) {
			$cache = Cache::get($cache_key);
			$data = json_decode($cache);
			if ($data->expire_time < time()) {
				// 如果是企业号用以下 URL 获取 ticket
				// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
				$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
				$res = json_decode(httpGet($url));
				$ticket = $res->ticket;
				if ($ticket) {
					$data->expire_time = time() + 7000;
					$data->jsapi_ticket = $ticket;
					Cache::forever($cache_key, json_encode($data));
				}
			} else {
				$ticket = $data->jsapi_ticket;
			}
		} else {
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode(httpGet($url));
			$ticket = $res->ticket;
			$cache = json_encode([
				'expire_time' => time(),
				'jsapi_ticket' => $ticket
			]);
			Cache::forever($cache_key, $cache);
		}

		return $ticket;
	}
}

if (! function_exists('createNonceStr')) {

	function createNonceStr($length = 16)
	{
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i ++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
}

if (! function_exists('getAccessToken')) {

	function getAccessToken($appid = '', $appsecret = '')
	{
		// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
		$cache_key = md5('weixin_jssdk_access_token');
		if (Cache::has($cache_key)) {
			$cache = Cache::get($cache_key);
			$data = json_decode($cache);
			if ($data->expire_time < time()) {
				// 如果是企业号用以下URL获取access_token
				// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
				$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
				$res = json_decode(httpGet($url));
				$access_token = $res->access_token;
				if ($access_token) {
					$data->expire_time = time() + 7000;
					$data->access_token = $access_token;
					Cache::forever($cache_key, json_encode($data));
				}
			} else {
				$access_token = $data->access_token;
			}
		} else {
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
			$res = json_decode(httpGet($url));
			$access_token = $res->access_token;
			$cache = json_encode([
				'expire_time' => time(),
				'access_token' => $access_token
			]);
			Cache::forever($cache_key, $cache);
		}

		return $access_token;
	}
}

if (! function_exists('httpGet')) {

	function httpGet($url, $domain = '', $user_agent = '', $acceptencoding = false, $header = false)
	{
		$curl = curl_init();
		if ($domain)
			curl_setopt($curl, CURLOPT_REFERER, $domain); //伪造来源
		if ($user_agent)
			curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); //伪造浏览器访问
		if ($acceptencoding)
			curl_setopt($curl, CURLOPT_ENCODING, "");
		if ($header)
			curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		curl_close($curl);

		if ($httpCode != 200) {
			return false;
		}

		return $res;
	}
}
//微信分享jssdk end


//微信网页授权函数
if (! function_exists('getAccessUser')) {

	function getAccessUser($app_id = '', $code = '', $appsecret = '')
	{

		//先获取access_token
		$access_info = getWebAccessToken($app_id, $appsecret, $code);

		//拉取用户信息
		$user_info = getUserInfo($access_info['access_token'], $access_info['openid']);

		//保存用户头像
		$user_avatar = null;
		if ($user_info['headimgurl']) {
			$user_avatar = fetchUserFile($user_info['headimgurl']);
		}

		return [
			'nickname' => $user_info['nickname'],
			'avatar_id' => is_null($user_avatar) ? '' : $user_avatar->id
		];
	}
}

if (! function_exists('getWebAccessToken')) {

	function getWebAccessToken($app_id = '', $appsecret = '', $code = '')
	{
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $app_id . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';

		$res = json_decode(httpGet($url));
		return [
			'access_token' => ! is_null($res) ? $res->access_token : '',
			'openid' => ! is_null($res) ? $res->openid : ''
		];
	}
}

if (! function_exists('getUserInfo')) {

	function getUserInfo($access_token = '', $openid = '')
	{
		$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

		$res = json_decode(httpGet($url));
		return [
			'nickname' => ! is_null($res) ? $res->nickname : '',
			'headimgurl' => ! is_null($res) ? $res->headimgurl : ''
		];
	}
}
//微信网页授权函数 end


/**
 *  对象下拉框
 */
if (! function_exists('form_select')) {

	function form_select($name, $list, $selected = null, $options = array(), $default = '', $sid = 'id', $sname = 'name')
	{
		$data = [];
		if ($default) {
			$data[''] = $default;
		}
		if ($list) {
			foreach ($list as $item) {
				$data[$item[$sid]] = $item[$sname];
			}
		}

		return Form::select($name, $data, $selected, $options);
	}
}

if (! function_exists('from_today')) {

	/**
	 * 距今天多少天
	 */
	function from_today($date)
	{
		$temp = time() - strtotime($date);
		$day = floor($temp / 86400);
		return $day;
	}
}

if (! function_exists('to_today')) {

	/**
	 * 距今天多少天
	 */
	function to_today($date)
	{
		$day = 0;
		if ($date > 0) {
			$temp = strtotime($date) - time();
			$day = ceil($temp / 86400);
		}
		return $day;
	}
}

if (! function_exists('is_mobile_request')) {

	/**
     * 判断是否手机访问
     * @return boolean
     */
	function is_mobile_request()
	{
		$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
		$mobile_browser = '0';
		if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
			$mobile_browser ++;
		if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
			$mobile_browser ++;
		if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
			$mobile_browser ++;
		if (isset($_SERVER['HTTP_PROFILE']))
			$mobile_browser ++;
		$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
		$mobile_agents = array(
			'w3c ',
			'acs-',
			'alav',
			'alca',
			'amoi',
			'audi',
			'avan',
			'benq',
			'bird',
			'blac',
			'blaz',
			'brew',
			'cell',
			'cldc',
			'cmd-',
			'dang',
			'doco',
			'eric',
			'hipt',
			'inno',
			'ipaq',
			'java',
			'jigs',
			'kddi',
			'keji',
			'leno',
			'lg-c',
			'lg-d',
			'lg-g',
			'lge-',
			'maui',
			'maxo',
			'midp',
			'mits',
			'mmef',
			'mobi',
			'mot-',
			'moto',
			'mwbp',
			'nec-',
			'newt',
			'noki',
			'oper',
			'palm',
			'pana',
			'pant',
			'phil',
			'play',
			'port',
			'prox',
			'qwap',
			'sage',
			'sams',
			'sany',
			'sch-',
			'sec-',
			'send',
			'seri',
			'sgh-',
			'shar',
			'sie-',
			'siem',
			'smal',
			'smar',
			'sony',
			'sph-',
			'symb',
			't-mo',
			'teli',
			'tim-',
			'tosh',
			'tsm-',
			'upg1',
			'upsi',
			'vk-v',
			'voda',
			'wap-',
			'wapa',
			'wapi',
			'wapp',
			'wapr',
			'webc',
			'winw',
			'winw',
			'xda',
			'xda-'
		);
		if (in_array($mobile_ua, $mobile_agents))
			$mobile_browser ++;
		if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
			$mobile_browser ++;
			// Pre-final check to reset everything if the user is on Windows
		if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
			$mobile_browser = 0;
			// But WP7 is also Windows, with a slightly different characteristic
		if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
			$mobile_browser ++;
		if ($mobile_browser > 0)
			return true;
		else
			return false;
	}
}

if (! function_exists('percent_round')) {

	/**
	 * 百分比显示
	 *
	 * @param $numerator 分子
	 * @param $denominator 分母
	 * @param int $prec  保留几位小数
	 * @return float|string
	 */
	function percent_round($numerator = 0, $denominator = 0, $prec = 2)
	{
		if ($denominator == 0) {
			return "0%";
		}
		return round($numerator / $denominator * 100, $prec) . "%";
	}
}

if (! function_exists('get_real_ip')) {

	/**
     * 获取真实ip
     */
	function get_real_ip()
	{
		if (isset($_SERVER)) {
			if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
				$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
			} else
				if (isset($_SERVER["HTTP_CLIENT_IP"])) {
					$realip = $_SERVER["HTTP_CLIENT_IP"];
				} else {
					$realip = $_SERVER["REMOTE_ADDR"];
				}
		} else {
			if (getenv("HTTP_X_FORWARDED_FOR")) {
				$realip = getenv("HTTP_X_FORWARDED_FOR");
			} else
				if (getenv("HTTP_CLIENT_IP")) {
					$realip = getenv("HTTP_CLIENT_IP");
				} else {
					$realip = getenv("REMOTE_ADDR");
				}
		}
		return $realip;
	}
}

if (! function_exists('array_json')) {

	/**************************************************************
	 *
	 *  将数组转换为JSON字符串（兼容中文）
	 * @param  array $array 要转换的数组
	 * @return string      转换得到的json字符串
	 * @access public
	 *
	 *************************************************************/
	function array_json($array)
	{
		arrayRecursive($array, 'urlencode', true);
		$json = json_encode($array);
		return urldecode($json);
	}
}

if (! function_exists('arrayRecursive')) {

	/**************************************************************
	 *
	 *  使用特定function对数组中所有元素做处理
	 * @param  string &$array 要处理的字符串
	 * @param  string $function 要执行的函数
	 * @return boolean $apply_to_keys_also     是否也应用到key上
	 * @access public
	 *
	 *************************************************************/
	function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
	{
		static $recursive_counter = 0;
		if (++ $recursive_counter > 1000) {
			die('possible deep recursion attack');
		}
		foreach ($array as $key => $value) {
			if (is_array($value)) {
				arrayRecursive($array[$key], $function, $apply_to_keys_also);
			} else {
				$array[$key] = $function($value);
			}
			if ($apply_to_keys_also && is_string($key)) {
				$new_key = $function($key);
				if ($new_key != $key) {
					$array[$new_key] = $array[$key];
					unset($array[$key]);
				}
			}
		}
		$recursive_counter --;
	}
}
if (! function_exists('guid')) {

	/**
     * 生成不重复的随机字符串
     * @return string
     */
	function guid()
	{
		$charid = md5(uniqid(mt_rand(), true));
		$uuid = substr($charid, mt_rand(0, 20), 8);
		return $uuid;
	}
}

if (! function_exists('getParameterItem')) {

	/**
	 *  获取参数
	 * @param string $pid
	 * @return mixed
	 */
	function getParameterItem($pid = '')
	{
		if ($pid) {
			$data = ParameterItem::where('pid', $pid)->latest('sort')->get();

			return $data;
		}
	}

	if (! function_exists('cal_days_in_month')) {

		/**
		 *
		 * @param string $month
		 * @param string $year
		 */
		function cal_days_in_month($calendar, $month, $year)
		{
			return date('t', mktime(0, 0, 0, $month, 1, $year));
		}
	}
	if (! defined('CAL_GREGORIAN'))
		define('CAL_GREGORIAN', 1);
}

if(!function_exists('_get_token')) {
    /**
     * 获取环信app管理员token
     */
    function _get_token()
    {
        $formgettoken = "https://a1.easemob.com/xmyundian/scmsnew/token";
        $post = array(
            "grant_type" => "client_credentials",
            "client_id" => "YXA6acmmwMi_EeW9QWHWyFBU6A",
            "client_secret" => "YXA6z0zgFVOcsBDXrjwlgjPzukJKafU"
        );
        $patoken = json_encode($post);
        $res = _curl_request($formgettoken, $patoken);
        $tokenResult = array();

        $tokenResult = json_decode($res, true);

        if (isset($tokenResult["access_token"])) {
            Cache::put('hx_access_token', "Authorization: Bearer " . $tokenResult["access_token"], $tokenResult["expires_in"] - 100);
        }
        
        return "Authorization: Bearer " . $tokenResult["access_token"];
    }
}

if(!function_exists('_curl_request')) {
    /**
     * 请求环信授权注册
     * @param unknown $url
     * @param unknown $body
     * @param unknown $header
     * @param string $method
     * @return string|unknown
     */
    function _curl_request($url, $body, $header = array(), $method = "POST",$clength = false)
    {
        array_push($header, 'Accept:application/json');
        array_push($header, 'Content-Type:application/json');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, $method, 1);

        switch ($method) {
            case "GET" :
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true);
                if($clength) {
                    array_push($header, 'Content-length: 0');
                }
                break;
            case "PUT" :
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }

        curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        if (isset($body{3}) > 0) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        if (count($header) > 0) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $ret = curl_exec($ch);
        $err = curl_error($ch);
        $curl_info = curl_getinfo($ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
//        var_dump($curl_info);exit;
        if ($err) {
            return $err;
        }
        return $ret;
    }
}

if(!function_exists('register_hx_user')) {
    /**
     * 注册环信用户
     * @param $mobile
     * @return string|unknown
     */
    function register_hx_user($mobile,$nickname = '')
    {
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users';    //环信授权注册接口

        $username = $mobile;

        $body = array(
            "username" => $username,
            "password" => 'scmi_user_password_' . $mobile,
            "nickname" => $nickname
        );
        $patoken = json_encode($body);

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token

        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, $patoken, $header);    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, $patoken, $header);    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return $res;
    }
}

if(!function_exists('create_chat_group')) {
    /**
     * 成立群组
     * @param $master_mobile
     * @param $members
     * @param $name
     * @param $description
     * @param int $maxusers
     * @return mixed
     */
    function create_chat_group($master_mobile,$members,$name,$description,$maxusers=100,$public=true){
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups';    //环信创建群组
//         $master_mobile = env('APP_DEBUG') ? md5('scmi_user_test' . $master_mobile) : md5('scmi_user_' . $master_mobile);
//        $master_mobile = md5('scmi_user_' . $master_mobile);
        $members_mobile = [];
        foreach($members as $item){
            $members_mobile[] = $item;
        }
        $body = array(
            "groupname" => $name,
            "desc" => $description,
            'public' => $public,
            'approval' => false,
            'maxusers' => $maxusers,
            'owner' => $master_mobile,
            "members" => $members_mobile
        );

        $patoken = json_encode($body);

//        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
//
//        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);
        $header = array(_get_token());

        $res = _curl_request($formgettoken, $patoken, $header);    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, $patoken, $header);    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}


if(!function_exists('delete_chat_group_user')) {
    /**
     * 环信群组删除成员
     * @param $group_id
     * @param $user_mobile
     * @return mixed
     */
    function delete_chat_group_user($group_id,$user_mobile){
//         $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id.'/users/'.$user_mobile;    //环信创建群组

        $header = array(_get_token());

        $res = _curl_request($formgettoken, '', $header,'DELETE');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'DELETE');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('add_chat_group_user')) {
    /**
     * 环信群组添加成员
     * @param $group_id
     * @param $user_mobile
     * @return mixed
     */
    function add_chat_group_user($group_id,$user_mobile){
//     	$server_user = ServeUser::where('username',$user_mobile)->first();
//     	if(is_null($server_user)){
//     		$app_user = User::where('phone',$user_mobile)->first();
//     		if(is_null($app_user)){
//     			$user = $user_mobile;
//     			register_hx_user_for_mobile($user);
//     		}else{
//     			$user = env('APP_DEBUG') ? md5('scmi_user_test' . $app_user->id) : md5('scmi_user_' . $app_user->id);
//     			register_hx_user($app_user->id);
//     		}
// //     		is_null($app_user) ? $user_mobile = $user_mobile : $user_mobile = $app_user->id; 
    		
//     	}else{
//     		$user = $user_mobile;
//     		register_hx_user_for_mobile($user);
//     	}
//         $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);

        //注册用户
    	register_hx_user($user_mobile);
    	
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id.'/users/'.$user_mobile;    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token

		if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'POST',true);    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header);    //重新注册
            //$arrayResult =  json_decode($res, true);
        }
        
        return json_decode($res,true);
    }
}

if(!function_exists('get_chatgroups_detail')) {
    /**
     * 获取聊天群详情
     * @param $group_id
     * @return mixed
     */
    function get_chatgroups_detail($group_id){
//        $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id;    //环信创建群组

        $header = array(_get_token());

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('get_user_chatgroups')) {
    /**
     * 获取用户所在聊天组
     * @param $user
     * @return mixed
     */
    function get_user_chatgroups($user_mobile){
//         $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$user_mobile.'/joined_chatgroups';    //环信创建群组

        $header = array(_get_token());

//        weiXinNotifyLog(implode(',',$header));

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('user_status')) {
    /**
     * 用户在线与离线
     */
    function user_status($imid){
//        $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);

        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$imid.'/status';    //在线与离线

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token

        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        $return_data = json_decode($res,true);
        $status = false;
        if(array_key_exists('data',$return_data)){
            if(array_key_exists($imid,$return_data['data'])) {
                if($return_data['data'][$imid] == 'online'){
                    $status = true;
                }else{
                    $status = false;
                }
            }else if(array_key_exists('stliu',$return_data['data'])){
                if($return_data['data']['stliu'] == 'online'){
                    $status = true;
                }else{
                    $status = false;
                }
            }
        }

        return $status;
    }
}

if(!function_exists('hx_friends')) {
	/**
	 * 获取用户好友列表
	 * @param $user
	 * @return mixed
	 */
	function hx_friend($user_mobile){
// 		$user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);
		$formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$user_mobile.'/contacts/users';    //环信创建群组

		$access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

		$res = _curl_request($formgettoken, '', $header,'GET');    //注册

		$arrayResult = json_decode($res, true);

		if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
			$header = array(_get_token());
			$res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
			//$arrayResult =  json_decode($res, true);
		}

		return json_decode($res,true);
	}
}

if(!function_exists('hx_be_friend')) {
	/**
	 * 加为好友
	 * @param $user
	 * @return mixed
	 */
	function hx_be_friend($user_mobile,$friend_mobile){
// 		$user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);//md5('scmi_user_' . $user_mobile);
// 		$friend = env('APP_DEBUG') ? md5('scmi_user_test' . $friend_mobile) : md5('scmi_user_' . $friend_mobile);
		$formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$user_mobile.'/contacts/users/'.$user_mobile;    //环信创建群组

		$access_token = Cache::get('hx_access_token');    //从缓存获取access_token
		if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

		$res = _curl_request($formgettoken, '', $header,'POST');    //注册

		$arrayResult = json_decode($res, true);

		if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
			$header = array(_get_token());
			$res = _curl_request($formgettoken, '', $header,'POST');    //重新注册
			//$arrayResult =  json_decode($res, true);
		}

		return json_decode($res,true);
	}
}

if(!function_exists('get_app_chatgroups')) {
    /**
     * 获取app下聊天群组
     * @return mixed
     */
    function get_app_chatgroups(){

        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups';    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('get_chatgroup_users')) {
    /**
     * 获取群组中的所有成员
     * @param $group_id
     * @return mixed
     */
    function get_chatgroup_users($group_id){

        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id.'/users';    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('delete_chatgroup')) {
    /**
     * 删除群组
     * @param $group_id
     * @return mixed
     */
    function delete_chatgroup($group_id){

        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id;    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'DELETE');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'DELETE');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('edit_chatgroup')) {
    /**
     * 编辑群组信息
     * @param $group_id
     * @param $group_name
     * @param $description
     * @param $maxusers
     * @param $owner
     * @return mixed
     */
    function edit_chatgroup($group_id,$group_name,$description,$maxusers,$owner){

        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/chatgroups/'.$group_id;    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $body = array(
            "groupname" => $group_name,
            "description" => $description,
            'maxusers' => $maxusers,
//             'owner' => $owner
        );

        $patoken = json_encode($body);

        $res = _curl_request($formgettoken, $patoken, $header,'PUT');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'PUT');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('get_friends')) {
    /**
     * 获取好友
     * @param unknown $owner_user
     * @return mixed
     */
    function get_friends($owner_user){
//         $user = env('APP_DEBUG') ? md5('scmi_user_test' . $owner_user) : md5('scmi_user_' . $owner_user);
        $formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$owner_user.'/contacts/users';    //环信创建群组

        $access_token = Cache::get('hx_access_token');    //从缓存获取access_token
        if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

        $res = _curl_request($formgettoken, '', $header,'GET');    //注册

        $arrayResult = json_decode($res, true);

        if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
            $header = array(_get_token());
            $res = _curl_request($formgettoken, '', $header,'GET');    //重新注册
            //$arrayResult =  json_decode($res, true);
        }

        return json_decode($res,true);
    }
}

if(!function_exists('register_hx_user_for_mobile')) {
	/**
	 * 通过手机注册环信用户
	 * @param $mobile
	 * @return string|unknown
	 */
	function register_hx_user_for_mobile($mobile,$nickname = '')
	{
		$formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users';    //环信授权注册接口

// 		$username = env('APP_DEBUG') ? md5('scmi_user_test' . $mobile) : md5('scmi_user_' . $mobile);

		$body = array(
				"username" => $mobile,
				"password" => $mobile,
				"nickname" => $nickname
		);
		$patoken = json_encode($body);

		$access_token = Cache::get('hx_access_token');    //从缓存获取access_token

		if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

		$res = _curl_request($formgettoken, $patoken, $header);    //注册

		$arrayResult = json_decode($res, true);

		if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
			$header = array(_get_token());
			$res = _curl_request($formgettoken, $patoken, $header);    //重新注册
			//$arrayResult =  json_decode($res, true);
		}

		return json_decode($res,true);
	}
}

if(!function_exists('delete_hx_user')) {
	/**
	 * 删除环信用户
	 * @param $mobile
	 * @return string|unknown
	 */
	function delete_hx_user($user_mobile)
	{
//         $server_user = ServeUser::where('username',$user_mobile)->first();
//         if(is_null($server_user)){
//             $user = env('APP_DEBUG') ? md5('scmi_user_test' . $user_mobile) : md5('scmi_user_' . $user_mobile);
//         }else{
//             $user = $user_mobile;
//         }

		$formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$user_mobile;    //环信授权注册接口

//		$body = array(
//				"nickname" => $nickname
//		);
//		$patoken = json_encode($body);

		$access_token = Cache::get('hx_access_token');    //从缓存获取access_token

		if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

		$res = _curl_request($formgettoken, '', $header,'DELETE');    //注册

		$arrayResult = json_decode($res, true);

		if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
			$header = array(_get_token());
			$res = _curl_request($formgettoken, '', $header,'DELETE');    //重新注册
			//$arrayResult =  json_decode($res, true);
		}

		return $res;
	}
}

if(!function_exists('edit_hx_user')) {
	/**
	 * 编辑环信用户
	 * @param $mobile
	 * @return string|unknown
	 */
	function edit_hx_user($imid)
	{
		$formgettoken = 'https://a1.easemob.com/xmyundian/scmsnew/users/'.$imid;    //环信授权注册接口


		$access_token = Cache::get('hx_access_token');    //从缓存获取access_token

		if (empty($access_token)) $header = array(_get_token()); else $header = array($access_token);

		$res = _curl_request($formgettoken, '', $header,'PUT');    //注册

		$arrayResult = json_decode($res, true);

		if (!empty($arrayResult['error_description']) && $arrayResult['error_description'] == 'Unable to authenticate due to expired access token') {        //token过期，重新获取token
			$header = array(_get_token());
			$res = _curl_request($formgettoken, '', $header,'PUT');    //重新注册
			//$arrayResult =  json_decode($res, true);
		}

		return $res;
	}
}

if(!function_exists('get_reserve_source')){
	/**
	 * 获取来源
	 */
	function get_reserve_source($source){
		$key = 'get_reserve_source'.$source;
		if (Cache::has($key)) {
			return Cache::get($key);
		}
		$data = ChannelSource::where('alias',$source)->first();
		if(is_null($data)){
			if(!Cache::has($key)) {
				Cache::put($key, null, 110);
			}
			return null;
		}else{
			Cache::put($key, $data ,110);
			return $data;
		}
	}
}